import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Drawer, Flex, Form, Select, Input, message } from "antd";
import { apiSysDictSelect } from '../../../services/common';
import { MinusCircleOutlined } from '@ant-design/icons';
import { apiPermissionEdit, apiPermissionView, apiPermissionEmailList } from '../../../services/permissionManager';
import { SYSCODE, CONFIG_ITEM_KEYS } from '../../../utils/constant';
import { getUserName, transformArray } from '../../../utils/commonUtil';
import '../index.scss';
import _ from 'lodash';

const EditModal = ({
  openDrawer,
  setOpenDrawer,
  editSucessFn,
  editType,
  recordData,
}) => {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const { TextArea } = Input;
  const [buList, setBuList] = useState([]);
  const [roleList, setRoleList] = useState([]);
  const [initialData, setInitialData] = useState();
  const { BU, SYS_ROLE } = CONFIG_ITEM_KEYS;

  const apiPermissionSaveSync = async (params) => {
    const { data } = await apiPermissionEdit({
      ...params,
      updatedBy: getUserName(),
    })
    if (data?.code === 200) {
      message.success(t('common.saveSuccess'));
      setOpenDrawer(false);
      editSucessFn();
    }
  };
  const saveClickHandle = () => {
    const params = form?.getFieldsValue();
    params.userId = initialData?.userId;
    console.log(params);
    form.validateFields().then(() => {
      apiPermissionSaveSync(params);
    }, () => {
      return false;
    });
  };
  const apiSysDictSelectAsync = async () => {
    const params = {
      sysCode: SYSCODE,
      dictCodes: [BU, SYS_ROLE]
    };
    const { data } = await apiSysDictSelect(params || { buType: recordData?.userId, userId: recordData?.userId });
    // 针对每个BUG 配置Role
    setBuList(transformArray(data?.data?.[BU]?.filter((item) => item !== 'All')));
    setRoleList(transformArray(data?.data?.[SYS_ROLE]));
  };
  const initModalData = async () => {
    apiSysDictSelectAsync();
    const resData = await apiPermissionView({ id: recordData?.userId });
    const detialData = resData?.data?.data?.item;
    setInitialData(detialData);
  };
  const addInite = () => {
    const userGroupsList = [
      ...form?.getFieldsValue()?.userGroups,
      {
        buType: '',
        userRole: []
      }
    ];
    form.setFieldValue('userGroups', userGroupsList);
  };
  useEffect(() => {
    initModalData();
  }, []);

  return (
    <>
      {
        initialData &&
        <Drawer
          className='permission-modal-wrap'
          title={t(`common.${editType}`)}
          footer={
            <Flex justify='flex-end'>
              <Button type="primary" onClick={saveClickHandle} disabled={editType === 'view'}>{t('common.save')}</Button>
            </Flex>
          }
          placement="right"
          onClose={() => setOpenDrawer(false)}
          open={openDrawer}
          width={600}>
          <Form form={form} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }} initialValues={initialData} disabled={editType === 'view'}>
            <Form.Item name="userEmail" label={t('common.email')}
              rules={[
                {
                  required: true,
                  message: t('common.selectRequired'),
                }
              ]}>
              <Input disabled placeholder={t('common.pleaseSelect')} />
            </Form.Item>
            <Form.Item name="userCampRole" label={t('permissionManagner.campRole')}
              rules={[
                {
                  required: true,
                  message: t('common.selectRequired'),
                }
              ]}>
              <Input disabled placeholder={t('common.pleaseSelect')} />
            </Form.Item>
            <Form.Item name="userModule" label={t('common.module')}
              rules={[
                {
                  required: true,
                  message: t('common.selectRequired'),
                }
              ]}>
              <Input disabled placeholder={t('common.pleaseSelect')} />
            </Form.Item>
            <Form.List name="userGroups">
              {(fields, { add, remove }) => (
                <div
                  key={fields.key}
                  className='form-list-wrap'
                  style={{
                    display: 'flex',
                    rowGap: 16,
                    flexDirection: 'column',
                  }}
                ><div className='zr-fied-required'>{t('common.userPermission')}</div>
                  <Flex className="items-header">
                    <span style={{ width: '210px' }}>{t('common.bu')}</span>
                    <span style={{ width: '350px' }}>{t('common.role')}</span>
                  </Flex>
                  {fields.map((field) => (
                    <Flex key={field.key}>
                      <Form.Item name={[field.name, 'buType']}
                        label=""
                        style={{ width: '200px', marginRight: '10px' }}
                        rules={[
                          {
                            required: true,
                            message: t('common.selectRequired'),
                          }
                        ]}>
                        <Select placeholder={t('common.pleaseSelect')} allowClear options={buList} />
                      </Form.Item>
                      <Form.Item name={[field.name, 'userRole']}
                        label=""
                        style={{ width: '350px', marginRight: '10px' }}
                        rules={[
                          {
                            required: true,
                            message: t('common.selectRequired'),
                          }
                        ]}>
                        <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={roleList} />
                      </Form.Item>
                      <Button onClick={() => remove(field.name)} icon={<MinusCircleOutlined style={{ fontSize: 20 }} />}></Button>
                    </Flex>
                  ))}
                </div>
              )}
            </Form.List>
            <Button type="primary"
              disabled={editType === 'view'}
              ghost style={{ width: "100px", marginTop: '10px' }}
              onClick={() => addInite()} block>
              {t('common.add')}
            </Button>
          </Form>
        </Drawer>
      }
    </>
  )
};

export default EditModal;